package org.rslai.tcedit.hibernate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;

public class myAnnotationSessionFactoryBean extends org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean {

	/**
	 * 指定 annotated读取映射的类
	 * 将org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean改为加载domain目录下的所有类
	 */
	@Override
	@SuppressWarnings("rawtypes")
	public void setAnnotatedClasses(Class[] annotatedClasses) {
		String packageStr = annotatedClasses[0].getPackage().getName() + ".";
		String packagePath = packageStr.replace('.', '/');

		Map<String, Class> annotatedClassesMap = new HashMap<String, Class>();
		
		for (Class clazz : annotatedClasses) {
			annotatedClassesMap.put(clazz.getSimpleName().toLowerCase(), clazz);
		}

		try {
			for (String fullName : (new ClassPathResource(packagePath)).getFile().list()) {
				int suffixIndexOf = fullName.toLowerCase().lastIndexOf(".class");
				if (suffixIndexOf != -1) {
					String fileName = fullName.substring(0, suffixIndexOf);
					if (!annotatedClassesMap.containsKey(fileName.toLowerCase())) {
						Class clazz = Class.forName(packageStr + fileName);
						annotatedClassesMap.put(clazz.getSimpleName().toLowerCase(), clazz);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		super.setAnnotatedClasses( (Class[]) annotatedClassesMap.values().toArray(new Class[annotatedClassesMap.size()]) );
	}

}
